const userService = require("../service/user.service");
const md5password = require("../utils/md5-password");
const jwt = require("jsonwebtoken")
const { privateKey } = require("../config/screct");
const profileService = require("../service/profile.service");


class UserController {
  async create(ctx, next) {
    // 1. 将用户信息存储到数据库中
    const user = ctx.request.body;
    // 使用md5算法加密密码
    user.password = md5password(user.password);
    const res = await userService.create(user);
    const id = res.insertId;
    const name = user.name;
    await profileService.insertUserMessage(id)
    // 2.生成token
    try {
      const token = jwt.sign({ id, name }, privateKey.toString(), {
        expiresIn: 24 * 60 * 60, //过期日期
        algorithm: "RS256", //加密算法
      });
      // 3.返回插入数据操作结果
      ctx.body = {
        status: 201, // 资源已经成功创建
        data: {
          token,
        },
      };
    } catch (err) {
      console.log(err);
    }
  }
}

module.exports = new UserController();
